package com.hongfasoft.model;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.hongfasoft.util.HttpRequestUtil;
import com.hongfasoft.util.MessageUtil;
import com.hongfasoft.wx.message.Article;
import com.hongfasoft.wx.message.NewsMessage;

/**
 * 天气预报服务
 * 
 * @author lanp
 * @since 2014-7-29 20:56:16
 * @version v1.0.1
 */
public class WeatherService
{

	/**
	 * GBK编码
	 * 
	 * @param source
	 * @return
	 */
	public static String urlEncodeGBK(String source)
	{
		String result = source;
		try
		{
			result = java.net.URLEncoder.encode(source, "GBK");
		} catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 获取天气预报XML信息并返回
	 * 
	 * @param source
	 * @return
	 */
	public static String getWeatherJson(String source)
	{
		String dst = null;
		// 组装查询地址
		String requestUrl = "http://apix.sinaapp.com/weather/?appkey=trialuser&city={keyWord}";
		// 对参数q的值进行urlEncode utf-8编码
		requestUrl = requestUrl.replace("{keyWord}", HttpRequestUtil.urlEncode(source, "UTF-8"));
		System.out.println(requestUrl);
		dst = HttpRequestUtil.httpRequest(requestUrl);
		return dst;
	}
	
	/**
	 * 获取今天、明天和后天的天气预报信息并返回
	 * 
	 * @param source
	 * @return
	 */
	public static String getWeatherInfo(Map<String, String> requMap)
	{
		String content = requMap.get("Content").trim();
		// 将歌曲2个字及歌曲后面的+、空格、-等特殊符号去掉
		String location = content.replaceAll("^天气[\\+ ~!@#%^-_=]?", "");

		if (location == null || location.length() == 0)
		{
			return getUsage();
		}

		String weatherJson = getWeatherJson(location);
		if (null == weatherJson || "".equals(weatherJson))
		{
			return null;
		}
		String keys[] = { "Title", "Description", "PicUrl", "Url" };
		List<Article> articleList = new ArrayList<Article>();
		JSONArray ja = JSONArray.fromObject(weatherJson);
		for (int i = 0; i < ja.size(); i++)
		{
			Article article = new Article();
			article.setTitle("" + ((JSONObject) ja.get(i)).get(keys[0]));
			article.setDescription("" + ((JSONObject) ja.get(i)).get(keys[1]));
			article.setPicUrl("" + ((JSONObject) ja.get(i)).get(keys[2]));
			article.setUrl("" + ((JSONObject) ja.get(i)).get(keys[3]));
			articleList.add(article);
		}
		// 发送方帐号（open_id）
		String fromUserName = requMap.get("FromUserName");
		// 公众帐号
		String toUserName = requMap.get("ToUserName");
		// 消息类型
		String msgType = requMap.get("MsgType");
		// 创建图文消息
		NewsMessage newsMessage = new NewsMessage();
		newsMessage.setToUserName(fromUserName);
		newsMessage.setFromUserName(toUserName);
		newsMessage.setCreateTime(new Date().getTime());
		newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
		newsMessage.setFuncFlag(0);

		newsMessage.setArticleCount(articleList.size());
		newsMessage.setArticles(articleList);

		return MessageUtil.newsMessageToXml(newsMessage);
	}

	/**
	 * 用法提示
	 * 
	 * @return
	 */
	public static String getUsage()
	{
		StringBuffer buffer = new StringBuffer();
		buffer.append("天气预报查看操作指南").append("\n\n");
		buffer.append("回复：天气+地址").append("\n");
		buffer.append("例如：天气上海").append("\n");
		return buffer.toString();
	}

}